const COS = require('cos-nodejs-sdk-v5');
const path = require('path');

class CosPlugin {
  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    compiler.hooks.afterEmit.tapPromise('CosPlugin', async compilation => {
      const cos = new COS({
        SecretId: this.options.SecretId,
        SecretKey: this.options.SecretKey,
      });

      // 清空存储桶内的文件
      await new Promise((resolve, reject) => {
        cos.getBucket(
          {
            Bucket: this.options.Bucket,
            Region: this.options.Region,
          },
          (err, data) => {
            if (err) {
              reject(err);
            } else {
              const objects = data.Contents.map(item => ({Key: item.Key}));
              if (!objects.length) return resolve();

              cos.deleteMultipleObject(
                {
                  Bucket: this.options.Bucket,
                  Region: this.options.Region,
                  Objects: objects,
                },
                (err, data) => {
                  if (err) {
                    console.log(err);
                    reject(err);
                  } else {
                    resolve(data);
                  }
                }
              );
            }
          }
        );
      });

      const assets = compilation.assets;
      const promises = [];

      for (const filename in assets) {
        const file = assets[filename];
        const filepath = path.join(compilation.outputOptions.path, filename);

        if (file.emitted && file.existsAt) {
          const promise = new Promise((resolve, reject) => {
            cos.putObject(
              {
                Bucket: this.options.Bucket,
                Region: this.options.Region,
                Key: filename,
                Body: file.source(),
              },
              (err, data) => {
                if (err) {
                  reject(err);
                } else {
                  resolve(data);
                }
              }
            );
          });

          promises.push(promise);
        }
      }

      await Promise.all(promises);
    });
  }
}

module.exports = CosPlugin;
